﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using learncoremvc.Models;
using learncoremvc.EF;
using Microsoft.EntityFrameworkCore;

namespace learncoremvc.Controllers
{
    public class HomeController : Controller
    {
        private static object Lock = new object();
        public IActionResult Index()
        {
            var obj = context.Blogs.Find(1);
            return View();
        }
        BloggingContext context;
  
       public HomeController(BloggingContext _context)
        {
            context = _context;
            

        }
      
        public  async Task<JsonResult> OrderOne()
        {
            using (var tran = context.Database.BeginTransaction())
            {
                try
                {
                   
                        var obj = context.Blogs.Find(1);
                        obj.postcount = obj.postcount - 1;
                        //Post onepost = new Post() { BlogId = 1, Content = "1111" };
                        await  context.SaveChangesAsync();
                        tran.Commit();
                        return Json(obj.postcount);
             
                 
                }
                catch (Exception)
                {
                    tran.Rollback();
                    return Json("error");
                    // TODOHandle failure
                }
            }
          
          
            //if(Startup.i>99)
            //{
            //    return Json(false);采用触发器在sqlserver来进行并发控制
            //}
            //Startup.i = Startup.i + 1;
            //Debug.WriteLine("i==" + Startup.i);
            //Post o = new Post() { Content = Startup.i.ToString(),BlogId=1};
            //context.Posts.Add(o);
            //context.SaveChanges();
            //return Json(true);

            //try
            //{


            //}
            //catch (DbUpdateConcurrencyException ex)
            //{
            //    foreach (var entry in ex.Entries)
            //    {
            //        if (entry.Entity is Blog)
            //        {
            //            // Using a NoTracking query means we get the entity but it is not tracked by the context
            //            // and will not be merged with existing entities in the context.
            //            var databaseEntity = context.Blogs.AsNoTracking().Single(p => p.BlogId == ((Blog)entry.Entity).BlogId);
            //            var databaseEntry = context.Entry(databaseEntity);

            //            foreach (var property in entry.Metadata.GetProperties())
            //            {
            //                var proposedValue = entry.Property(property.Name).CurrentValue;
            //                var originalValue = entry.Property(property.Name).OriginalValue;
            //                var databaseValue = databaseEntry.Property(property.Name).CurrentValue;

            //                // TODO: Logic to decide which value should be written to database
            //                // entry.Property(property.Name).CurrentValue = <value to be saved>;

            //                // Update original values to
            //                entry.Property(property.Name).OriginalValue = databaseEntry.Property(property.Name).CurrentValue;
            //            }
            //        }
            //        else
            //        {
            //            throw new NotSupportedException("Don't know how to handle concurrency conflicts for " + entry.Metadata.Name);
            //        }
            //    }

            //    // Retry the save operation
            //    context.SaveChanges();
            //    return Json(objblog.postcount);
            //}
            //  return Json(objblog.postcount);
        }
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
